import { Router } from '@angular/router';
import { OrganizationService } from './../../../../../services/organization.service';
import { EditDepartmentModalComponent } from './edit-department-modal/edit-department-modal.component';
import { Component, Input, OnInit, Output, ViewContainerRef, EventEmitter } from '@angular/core';
import { NzModalService } from 'ng-zorro-antd/modal';
import { NzMessageService } from 'ng-zorro-antd/message';
import { ExceptionHandler } from 'src/app/handler/exception.handler';
import { DepartmentService } from 'src/app/services/department.service';

@Component({
  selector: 'zepride-org-department-list',
  templateUrl: './org-department-list.component.html',
  styleUrls: ['./org-department-list.component.less']
})
export class OrgDepartmentListComponent implements OnInit {
  departmentList = [];
  @Input() orgId: string;
  @Output() onDepartmentSaved = new EventEmitter<any>();
  constructor(
    private modal: NzModalService,
    private viewContainerRef: ViewContainerRef,
    private departmentService: DepartmentService,
    private msg: NzMessageService,
    private orgSvr: OrganizationService,
    private router: Router
  ) { }

  async ngOnInit() {
    await this.getDepartmentNodes();
    await this.getOrgUserTree();
  }

  async getDepartmentNodes() {
    try {
      this.departmentList = await this.orgSvr.getOrganizationTrees({ organizationId: this.orgId, objectName: "Department" });
    } catch (error) {
      ExceptionHandler.current.handleError(error);
    }
  }

  private async getOrgUserTree() {
    try {
      let userList: any[] = await this.orgSvr.getOrganizationTrees({ organizationId: this.orgId, objectName: "User" });
      for (let department of this.departmentList) {
        department.users = userList.filter(x => x.parentId == department.id);
        if (department.object.leaderPerson) {
          let leader = userList.find(x => x.objectId == department.object.leaderPerson);
          department.leader = leader;
        }
      }
    } catch (error) {
      ExceptionHandler.current.handleError(error);
    }
  }

  editDepartment(item) {
    const modal = this.modal.create({
      nzTitle: '编辑部门',
      nzContent: EditDepartmentModalComponent,
      nzViewContainerRef: this.viewContainerRef,
      nzComponentParams: {
        departmentInfo: item.object,
        organizationId: this.orgId
      },
      nzFooter: null
    });

    modal.afterClose.subscribe(this.modalResultHandle.bind(this));
  }

  addDepartment() {
    const modal = this.modal.create({
      nzTitle: '创建部门',
      nzContent: EditDepartmentModalComponent,
      nzViewContainerRef: this.viewContainerRef,
      nzComponentParams: {
        organizationId: this.orgId
      },
      nzFooter: null
    });

    modal.afterClose.subscribe(this.modalResultHandle.bind(this));
  }

  private modalResultHandle(result) {
    if (result == 'ok') {
      this.msg.success('保存成功！');
      this.onDepartmentSaved.emit();
      this.ngOnInit();
    }
  }

  deleteDepartment(item) {
    this.modal.confirm({
      nzTitle: `是否要删除部门【${item.nodeName}】`,
      nzContent: `将删除部门下所有数据和信息！`,
      nzOkText: '删除',
      nzOkType: 'danger',
      nzOnOk: async () => {
        try {
          await this.departmentService.deleteDepartment(item.objectId);
          this.ngOnInit();
          this.onDepartmentSaved.emit();
        } catch (error) {
          this.msg.error(error.error.message);
        }
      },
      nzCancelText: '取消',
      nzOnCancel: () => console.log('Cancel')
    });
  }

  goToUserPage(item) {
    this.router.navigate(['home/employeeList'], { queryParams: { departmentNodeId: item.id } })
  }
}
